import React, { useState, useEffect } from "react";

interface NumberScrollerProps {
  targetNumber: number | string; // 可以传入数字或字符串
  duration?: number; // 持续时间，单位为毫秒
  type?: "money" | "default"; // 新增类型属性
}

const NumberScroller: React.FC<NumberScrollerProps> = ({
  targetNumber,
  duration = 2000,
  type,
}) => {
  // 检查 targetNumber 是否为有效的数字
  if (
    typeof targetNumber !== "number" &&
    !targetNumber
      .split("")
      .every((char: any) => (char >= "0" && char <= "9") || char === ".")
  ) {
    return <div>{targetNumber}</div>;
  }

  const targetValue =
    typeof targetNumber === "number" ? targetNumber : parseFloat(targetNumber);
  const [currentNumber, setCurrentNumber] = useState<number>(0);

  useEffect(() => {
    const startTime = Date.now();
    const endTime = startTime + duration;

    const updateNumber = () => {
      const now = Date.now();
      const progress = Math.min((now - startTime) / duration, 1);
      const newNumber = parseFloat((progress * targetValue).toFixed(2)); // 保留小数点后两位

      setCurrentNumber(newNumber);

      if (progress < 1) {
        requestAnimationFrame(updateNumber);
      }
    };

    updateNumber();
  }, [targetValue, duration]);

  // 根据类型格式化数字
  const formatNumber = (num: number): string => {
    if (type === "money") {
      return new Intl.NumberFormat("en-US", {
        style: "currency",
        currency: "USD",
      })
        .format(num)
        .replace("$", "");
    }
    return num.toString(); // 默认以字符串形式返回
  };

  return <div className="currentNumber">{formatNumber(currentNumber)}</div>;
};

export default NumberScroller;
